#主要功能：
# 1. 输入城市名称，获取当前天气信息。   
# 2. 根据openWeatherMap API提供的信息，返回当前天气信息。
# 3. 支持中英文输入。
import os
import json
import requests
from openai import OpenAI

# 初始化OpenAI客户端
client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),  # 替换为你的API密钥
    base_url="https://api.deepseek.com/v1"  # DeepSeek API端点
)

# 设置OpenWeatherMap API密钥
OPENWEATHER_API_KEY = "d94892357e6b825afa1c15556492f40e"  # 替换为你的OpenWeatherMap API密钥

def translate_chinese_to_english(city_name):
    """将中文城市名称翻译为英文"""
    # 常见城市的中英对照表
    city_mapping = {
        "北京": "Beijing",
        "上海": "Shanghai",
        "广州": "Guangzhou",
        "深圳": "Shenzhen",
        "杭州": "Hangzhou",
        "成都": "Chengdu",
        "重庆": "Chongqing",
        "武汉": "Wuhan",
        "西安": "Xi'an",
        "苏州": "Suzhou",
        "南京": "Nanjing",
        "天津": "Tianjin",
        "长沙": "Changsha",
        "厦门": "Xiamen",
        "青岛": "Qingdao",
        "大连": "Dalian",
        "哈尔滨": "Harbin",
        "沈阳": "Shenyang",
        "台北": "Taipei",
        "香港": "Hong Kong",
        "澳门": "Macau"
    }
    
    # 如果城市在对照表中，直接返回英文名
    if city_name in city_mapping:
        return city_mapping[city_name]
    
    # 如果不在对照表中，使用模型翻译（这里简化处理，实际可以调用翻译API）
    # 注意：这里只是示例，实际应用中可能需要更健壮的翻译方法
    try:
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "你是一个翻译助手，将中文地名翻译成英文。"},
                {"role": "user", "content": f"请将以下中文城市名称翻译成英文，只需返回英文名称，不要解释或其他内容：{city_name}"}
            ],
            temperature=0,
        )
        translated_name = response.choices[0].message.content.strip()
        return translated_name
    except Exception as e:
        print(f"翻译城市名称失败: {e}")
        return city_name  # 如果翻译失败，返回原名称（可能API不支持）

def get_current_weather(location):
    """获取指定城市的当前天气信息"""
    # 先将中文城市名称转换为英文
    english_location = translate_chinese_to_english(location)
    
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": english_location,
        "appid": OPENWEATHER_API_KEY,
        "units": "metric",  # 使用摄氏温度
        "lang": "zh_cn"     # 中文描述
    }
    
    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()
        weather_data = response.json()
        
        # 解析天气数据
        weather_info = {
            "location": location,  # 返回用户原始输入的中文名称
            "temperature": weather_data["main"]["temp"],
            "description": weather_data["weather"][0]["description"],
            "humidity": weather_data["main"]["humidity"],
            "wind_speed": weather_data["wind"]["speed"],
            "icon": weather_data["weather"][0]["icon"]
        }
        return json.dumps(weather_info)
    except Exception as e:
        return json.dumps({"error": f"获取天气失败: {str(e)}"})

def run_conversation():
    # 初始化对话历史
    messages = [
        {"role": "system", "content": "你是一个友好的助手，可以帮助用户查询天气信息。请用中文回答。"}
    ]
    
    print("助手: 你好！我可以帮你查询天气信息。你可以问我任何城市的天气情况。")
    
    while True:
        user_input = input("你: ")
        
        if user_input.lower() in ["退出", "exit", "quit", "bye"]:
            print("助手: 再见！祝你有个愉快的一天！")
            break
            
        # 添加用户消息到对话历史
        messages.append({"role": "user", "content": user_input})
        
        # 第一步：发送对话和函数信息给模型
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            tools=[{
                "type": "function",
                "function": {
                    "name": "get_current_weather",
                    "description": "获取指定城市的当前天气信息",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "location": {
                                "type": "string",
                                "description": "城市名称英文，例如'Beijing'或'New York'"
                            }
                        },
                        "required": ["location"]
                    }
                }
            }],
            tool_choice="auto",
        )
        
        response_message = response.choices[0].message
        tool_calls = response_message.tool_calls
        
        # 第二步：检查模型是否想要调用函数
        if tool_calls:
            # 第三步：调用函数
            messages.append(response_message)  # 将模型的响应添加到对话历史
            
            available_functions = {
                "get_current_weather": get_current_weather,
            }
            
            for tool_call in tool_calls:
                function_name = tool_call.function.name
                function_to_call = available_functions[function_name]
                function_args = json.loads(tool_call.function.arguments)
                function_response = function_to_call(location=function_args["location"])
                
                # 第四步：将函数响应发送给模型
                messages.append({
                    "tool_call_id": tool_call.id,
                    "role": "tool",
                    "name": function_name,
                    "content": function_response,
                })
            
            # 获取模型的最终响应
            second_response = client.chat.completions.create(
                model="deepseek-chat",
                messages=messages,
            )
            
            assistant_reply = second_response.choices[0].message.content
            messages.append({"role": "assistant", "content": assistant_reply})
            print(f"助手-天气: {assistant_reply}")
        else:
            assistant_reply = response_message.content
            messages.append({"role": "assistant", "content": assistant_reply})
            print(f"助手: {assistant_reply}")

if __name__ == "__main__":
    run_conversation()